package org.base23.video.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.base23.video.domain.entity.AiGuidanceConversationEntity;
import org.base23.video.mapper.AiGuidanceConversationMapper;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * AI指导对话会话 Repository
 */
@Repository
public class AiGuidanceConversationRepository extends ServiceImpl<AiGuidanceConversationMapper, AiGuidanceConversationEntity> {

    /**
     * 根据ID查询会话
     */
    public AiGuidanceConversationEntity findById(String id) {
        return getById(id);
    }

    /**
     * 保存会话
     */
    public boolean saveConversation(AiGuidanceConversationEntity conversation) {
        if (conversation.getId() == null) {
            conversation.setCreateTime(LocalDateTime.now());
            conversation.setLastUpdateTime(LocalDateTime.now());
            return save(conversation);
        } else {
            conversation.setLastUpdateTime(LocalDateTime.now());
            return updateById(conversation);
        }
    }

    /**
     * 根据用户ID分页查询对话
     */
    public IPage<AiGuidanceConversationEntity> findPageByUserId(String userId, String status, int current, int size) {
        Page<AiGuidanceConversationEntity> page = new Page<>(current, size);
        return baseMapper.selectPageByUserId(page, userId, status);
    }

    /**
     * 根据用户ID和运动类型查询活跃对话
     */
    public List<AiGuidanceConversationEntity> findActiveConversationsByUserAndSport(String userId, String sportType) {
        return baseMapper.selectByUserIdAndSportType(userId, sportType, "ACTIVE");
    }

    /**
     * 查询用户最近的对话
     */
    public AiGuidanceConversationEntity findLatestByUserId(String userId) {
        LambdaQueryWrapper<AiGuidanceConversationEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiGuidanceConversationEntity::getUserId, userId)
               .orderByDesc(AiGuidanceConversationEntity::getLastUpdateTime)
               .last("LIMIT 1");
        return getOne(wrapper);
    }

    /**
     * 更新消息数量
     */
    public boolean updateMessageCount(String conversationId, Integer count) {
        return baseMapper.updateMessageCount(conversationId, count) > 0;
    }

    /**
     * 查询过期的对话
     */
    public List<AiGuidanceConversationEntity> findExpiredConversations(LocalDateTime expireTime) {
        return baseMapper.selectExpiredConversations(expireTime);
    }

    /**
     * 批量删除过期对话
     */
    public int deleteExpiredConversations(LocalDateTime expireTime) {
        return baseMapper.deleteExpiredConversations(expireTime);
    }

    /**
     * 结束对话
     */
    public boolean endConversation(String conversationId) {
        AiGuidanceConversationEntity conversation = findById(conversationId);
        if (conversation != null) {
            conversation.setStatus("COMPLETED");
            conversation.setEndTime(LocalDateTime.now());
            conversation.setLastUpdateTime(LocalDateTime.now());
            return updateById(conversation);
        }
        return false;
    }

    /**
     * 统计用户对话数量
     */
    public long countByUserId(String userId) {
        LambdaQueryWrapper<AiGuidanceConversationEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiGuidanceConversationEntity::getUserId, userId);
        return count(wrapper);
    }
    
    /**
     * 根据结果ID和用户ID查询活跃会话
     */
    public AiGuidanceConversationEntity findActiveConversationByResultIdAndUserId(String resultId, String userId) {
        LambdaQueryWrapper<AiGuidanceConversationEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiGuidanceConversationEntity::getResultId, resultId)
               .eq(AiGuidanceConversationEntity::getUserId, userId)
               .eq(AiGuidanceConversationEntity::getStatus, AiGuidanceConversationEntity.ConversationStatus.ACTIVE.getCode())
               .orderByDesc(AiGuidanceConversationEntity::getLastUpdateTime)
               .last("LIMIT 1");
        return getOne(wrapper);
    }
} 